package cn.lls.interceptor;

import cn.lls.base.common.LlsEnum;
import cn.lls.base.common.UnAuthResult;
import cn.lls.base.exception.LlsException;
import cn.lls.base.result.ResultCode;
import cn.lls.base.util.TokenUtil;
import cn.lls.entity.admin.SuperadminEntity;
import cn.lls.entity.company.CompanyAccountEntity;
import cn.lls.service.ICompanyAccountService;
import cn.lls.service.ISuperadminService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截器的通用操作，此类不做拦截，仅为了减少代码重复量
 *
 * @ClassName CommonInterceptor
 * @Author 划水艺术家
 * @Date 2022/11/21 19:24
 * @Version 1.0
 **/

@Component
@Slf4j
public class MutualInterceptor {

    @Autowired
    private ISuperadminService superadminService;

    @Autowired
    private ICompanyAccountService companyAccountService;


    public Boolean preHandle(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse, Object o,
                                    String needIdentity) throws IOException {
        // 从请求头部获取 token
        if (HttpMethod.OPTIONS.toString().equals(httpServletRequest.getMethod())) {
            return true;
        }
        String token = httpServletRequest.getHeader("token");
        log.info("token = {}", token);
//        token = httpServletRequest.getParameter("token");
//        log.info("token2 = {}", token);
        if (StringUtils.isBlank(token)) {
            // 无 token，直接响应未登录
            UnAuthResult.returnUnauthorized(httpServletResponse, ResultCode.LOGIN_AUTH);
            return false;
        }
        Long userId = null;
        String identity = null;
        try {
            // 获取用户 Id 以及 身份
            userId = TokenUtil.getUserId(token);
            identity = TokenUtil.getIdentify(token);
        } catch (LlsException e) {
            UnAuthResult.returnUnauthorized(httpServletResponse, e.getCode(), e.getMessage());
            return false;
        } catch (Exception e) {
            UnAuthResult.returnUnauthorized(httpServletResponse, ResultCode.TOKEN_VOID);
            return false;
        }
        // 仅判断 token 是否为空且是否有效
        if (StringUtils.isEmpty(needIdentity))
            return true;
//        log.info("userId=  {}  iden = {}", userId, identity);
        // 验证超级管理员
        if (needIdentity.equals(LlsEnum.LlsIdentify.SUPER_ADMIN.getIdentify())){
//            log.info("超管", needIdentity);
            SuperadminEntity sa = superadminService.getById(Integer.parseInt(userId.toString()));
            if (sa == null){
                UnAuthResult.returnUnauthorized(httpServletResponse, ResultCode.ACCOUNT_NOT_EXISTS);
                return false;
            }
            if (!identity.equals(LlsEnum.LlsIdentify.SUPER_ADMIN.getIdentify())){
                UnAuthResult.returnUnauthorized(httpServletResponse, ResultCode.PERMISSION);
                return false;
            }
            return true;
        }
        // 验证公司管理员
        if (needIdentity.equals(LlsEnum.LlsIdentify.COMPANY_ADMIN.getIdentify())){
//            log.info("单管 {}", needIdentity);
            CompanyAccountEntity ca = companyAccountService.getById(userId);
//            log.info("ca = {}", ca);
            if (ca == null){
                UnAuthResult.returnUnauthorized(httpServletResponse, ResultCode.ACCOUNT_NOT_EXISTS);
                return false;
            }
            if (!identity.equals(LlsEnum.LlsIdentify.COMPANY_ADMIN.getIdentify())){
                UnAuthResult.returnUnauthorized(httpServletResponse, ResultCode.PERMISSION);
                return false;
            }
            return true;
        }
        return false;
    }

}
